<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input
          v-model="searchForm.fileResourceName"
          placeholder="实验室原始记录表名称"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#ECF3FC' }"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="index" width="50" label="序号" align="center" />
      <el-table-column
        prop="projectName"
        label="项目名称"
        width="200px"
        align="center"
      />
      <el-table-column
        prop="inspectionName"
        label="受检单位"
        width="250px"
        align="center"
      />
      <el-table-column
        prop="fileResourceName"
        label="实验室原始记录表名称"
        width="300"
        align="center"
      />
      <!-- 检测对象 -->
      <el-table-column prop="secdClassName" label="检测对象" align="center">
        <template slot-scope="{ row }">
          <div
            v-if="
              row.checkFactorInfoDetailVos &&
                row.checkFactorInfoDetailVos.length > 0
            "
          >
            <div
              v-for="(child, index) in row.checkFactorInfoDetailVos"
              :key="index"
              style="border:1px solid #e6ebf5;margin: -1px -11px -1px -11px;padding-top: 5px;padding-bottom: 2px;"
            >
              {{ child.secdClassName }}
            </div>
          </div>
          <span v-else>{{ row.secdClassName }}</span>
        </template>
      </el-table-column>

      <!-- 检测类别 -->
      <el-table-column prop="secdClassName" label="检测类别" align="center">
        <template slot-scope="{ row }">
          <div
            v-if="
              row.checkFactorInfoDetailVos &&
                row.checkFactorInfoDetailVos.length > 0
            "
          >
            <div
              v-for="(child, index) in row.checkFactorInfoDetailVos"
              :key="index"
              style="border:1px solid #e6ebf5;margin: -1px -11px -1px -11px;padding-top: 5px;padding-bottom: 2px;"
            >
              {{ child.secdClassName }}
            </div>
          </div>
          <span v-else>{{ row.secdClassName }}</span>
        </template>
      </el-table-column>

      <!-- 检测因子 -->
      <el-table-column
        prop="factorName"
        label="检测因子"
        align="center"
        width="400"
      >
        <template slot-scope="{ row }">
          <div
            v-if="
              row.checkFactorInfoDetailVos &&
                row.checkFactorInfoDetailVos.length > 0
            "
          >
            <div
              v-for="(child, index) in row.checkFactorInfoDetailVos"
              :key="index"
              style="border:1px solid #e6ebf5;margin: -1px -11px -1px -11px;padding-top: 5px;padding-bottom: 2px;"
            >
              {{ child.factorName }}
            </div>
          </div>
          <span v-else>{{ row.factorName }}</span>
        </template>
      </el-table-column>

      <!-- 样品编号 -->
      <el-table-column
        prop="sampleNo"
        label="样品编号"
        align="center"
        width="180"
      >
        <template slot-scope="{ row }">
          <div
            v-if="
              row.checkFactorInfoDetailVos &&
                row.checkFactorInfoDetailVos.length > 0
            "
          >
            <div
              v-for="(child, index) in row.checkFactorInfoDetailVos"
              :key="index"
              style="border:1px solid #e6ebf5;margin: -1px -11px -1px -11px;padding-top: 5px;padding-bottom: 2px;"
            >
              {{ child.sampleNo }}
            </div>
          </div>
          <span v-else>{{ row.sampleNo }}</span>
        </template>
      </el-table-column>

      <!-- 采样地点 -->
      <el-table-column
        prop="factorPoint
"
        label="采样地点"
        align="center"
      >
        <template slot-scope="{ row }">
          <div
            v-if="
              row.checkFactorInfoDetailVos &&
                row.checkFactorInfoDetailVos.length > 0
            "
          >
            <div
              v-for="(child, index) in row.checkFactorInfoDetailVos"
              :key="index"
              style="border:1px solid #e6ebf5;margin: -1px -11px -1px -11px;padding-top: 5px;padding-bottom: 2px;"
            >
              {{ child.factorPoint }}
            </div>
          </div>
          <span v-else>{{ row.factorPoint }}</span>
        </template>
      </el-table-column>

      <!-- 分析方法 -->
      <el-table-column
        prop="analysisMethod"
        label="分析方法"
        align="center"
        width="180"
      >
        <template slot-scope="{ row }">
          <div
            v-if="
              row.checkFactorInfoDetailVos &&
                row.checkFactorInfoDetailVos.length > 0
            "
          >
            <div
              v-for="(child, index) in row.checkFactorInfoDetailVos"
              :key="index"
              style="border:1px solid #e6ebf5;margin: -1px -11px -1px -11px;padding-top: 5px;padding-bottom: 2px;"
            >
              {{ child.analysisMethod }}
            </div>
          </div>
          <span v-else>{{ row.analysisMethod }}</span>
        </template>
      </el-table-column>

      <!-- 检测结果 -->
      <el-table-column
        prop="result"
        label="检测结果"
        align="center"
        v-if="showResultColumn"
      >
        <template slot-scope="{ row }">
          <div
            v-if="
              row.checkFactorInfoDetailVos &&
                row.checkFactorInfoDetailVos.length > 0
            "
          >
            <div
              v-for="(child, index) in row.checkFactorInfoDetailVos"
              :key="index"
              style="border:1px solid #e6ebf5;margin: -1px -11px -1px -11px;padding-top: 5px;padding-bottom: 2px;"
            >
              <span v-if="child.isFactor == 0 && child.checkRes">
                {{ child.checkRes.v1 ? child.checkRes.v1 : 0 }}×10<sup>{{
                  child.checkRes.v2 ? Number(child.checkRes.v2) : 0
                }}</sup
                >{{ child.unitName }}
              </span>
              <span v-else-if="child.isFactor == 1 && child.checkSubRes">
                {{ child.checkSubRes.v1 ? child.checkSubRes.v1 : 0 }}×10<sup>{{
                  child.checkSubRes.v2 ? Number(child.checkSubRes.v2) : 0
                }}</sup
                >{{ child.unitName }}
              </span>
              <span v-else>无结果</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="reviewType"
        label="检测状态"
        align="center"
        width="120"
      >
        <template slot-scope="{ row }">
          <el-tag :type="statusType(row.reviewType)">
            {{ statusText(row.reviewType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="240" align="center">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" @click="viewResult(row)"
            >表单结果查看</el-button
          >
          <el-divider direction="vertical" />
          <el-button size="mini" type="text" @click="viewAttachment(row)"
            >附件查看</el-button
          >
          <el-divider direction="vertical" />
          <el-button
            size="mini"
            type="text"
            v-if="row.reviewType == '2' || row.reviewType == '5'"
            @click="viewReason(row)"
            >驳回原因</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="row.reviewType == '0'"
            @click="withdrawForm(row)"
            >表单撤回</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="float: right; margin-top: 10px;">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="searchForm.pageNumber"
        :limit.sync="searchForm.pageSize"
        @pagination="handleSearch"
      />
    </div>

    <el-dialog
      title="驳回原因"
      :visible.sync="reasonDialogVisible"
      width="500px"
      @close="closeReasonDialog"
    >
      <div class="reason-content">
        <!-- 审核 -->
        <div class="checkStatus-item">
          <div class="checkStatus-label">
            <span style="border-left: 3px solid #409eff; padding-left: 8px;"
              >审核</span
            >
          </div>
          <div class="checkStatus-value" style="color: red;">驳回</div>
        </div>

        <!-- 审核意见 -->
        <div class="opinion-item">
          <div style="font-weight: bold; margin-bottom: 5px;">审核意见：</div>
          <div>{{ auditOpinion }}</div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="reasonDialogVisible = false"
          >关闭</el-button
        >
      </span>
    </el-dialog>

    <!-- 结果查看弹框 -->
    <el-dialog
      title="表单结果查看"
      :visible.sync="resultDialogVisible"
      width="80%"
      @close="closeResultDialog"
    >
      <div style="display: flex">
        <!-- 左侧：原始记录表 -->
        <div class="left-form">
          <div style="display: flex;flex-direction: row-reverse; gap: 10px;">
            <el-button size="mini" type="primary" @click="toggleEditMode">
              下载实验室原始记录表
            </el-button>
          </div>
          <!-- 修改为遍历展示多个表格 -->
          <div v-for="(table, index) in parsedTables" :key="index">
            <div
              v-html="table"
              class="dynamic-table"
              :class="{ 'edit-mode': isEditMode }"
              @click="handleTableCellClick"
            ></div>
            <!-- 在表格之间添加分隔线 -->
            <div
              v-if="index < parsedTables.length - 1"
              class="table-divider"
            ></div>
          </div>
        </div>

        <!-- 右侧：检测结果录入 -->
        <div class="right-form">
          <h2>检测结果信息</h2>

          <!-- 检测仪器 -->
          <el-form
            :model="batchData"
            label-width="90px"
            size="small"
            style="margin-bottom: 20px;"
          >
            <el-form-item
              label="项目名称："
              style="background: #fff;border-radius: 15px;margin-top: 10px;height: 50px;padding-top: 10px;"
            >
              {{ projectName }}
            </el-form-item>
            <el-form-item
              label="受检单位："
              style="background: #fff;border-radius: 15px;margin-top: 10px;height: 50px;padding-top: 10px;"
            >
              {{ inspectionName }}
            </el-form-item>
            <el-form-item
              label="检测仪器："
              style="background: #fff;border-radius: 15px;margin-top: 10px;height: 70px;padding-top: 20px;"
            >
              <el-row>
                <span
                  v-if="
                    batchData &&
                      batchData.length > 0 &&
                      batchData[0].checkEquipment
                  "
                >
                  {{ formatEquipmentInfo(batchData[0].checkEquipment) }}
                </span>
                <span v-else>暂无仪器信息</span>
              </el-row>
            </el-form-item>
          </el-form>

          <div class="sample-group">
            <el-form label-width="100px" label-position="left">
              <div
                v-for="(item, index) in batchData"
                :key="index"
                class="factor-section factor-package"
              >
                <!-- 因子 -->
                <div v-if="item.isFactor == 0" class="factor-package-item">
                  <el-form-item label="样品编号:">{{
                    item.sampleNo
                  }}</el-form-item>
                  <el-form-item label="检测因子:">{{
                    item.factorName
                  }}</el-form-item>
                  <el-form-item label="检测结果:">
                    <span>
                      {{ item.checkRes.v1 ? item.checkRes.v1 : 0 }}×10<sup>{{
                        item.checkRes.v2 ? Number(item.checkRes.v2) : 0
                      }}</sup
                      >{{ item.unitName }}
                    </span>
                  </el-form-item>
                </div>

                <!-- 因子套餐 -->
                <div
                  v-else-if="item.isFactor == 1"
                  class="factor-section factor-package"
                >
                  <div
                    v-for="(items, indexs) in Array.isArray(
                      item.factorSubsetVos
                    )
                      ? item.factorSubsetVos
                      : [item.factorSubsetVos]"
                    :key="indexs"
                    class="factor-package-item"
                  >
                    <el-form-item label="样品编号:">{{
                      items.sampleNo || item.sampleNo
                    }}</el-form-item>
                    <el-form-item label="检测因子:">{{
                      items.factorName
                    }}</el-form-item>
                    <el-form-item label="检测结果:">
                      <span>
                        {{
                          items.checkSubRes.v1 ? items.checkSubRes.v1 : 0
                        }}×10<sup>{{
                          items.checkSubRes.v2
                            ? Number(items.checkSubRes.v2)
                            : 0
                        }}</sup
                        >{{ items.unitName }}
                      </span>
                    </el-form-item>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeResultDialog">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as hisLabor from "@/api/hisLaborList";
import * as batchesServer from "@/api/batches";
import Pagination from "@/components/Pagination";

export default {
  components: { Pagination },
  data() {
    return {
      searchForm: {
        fileResourceName: "",
        jobId: "",
        pageNumber: 1,
        pageSize: 10
      },
      inspectionName: "",
      projectName:"",
      tableData: [],
      total: 0,
      batchData: [],
      tableHtml: "",
      tableStyle: "",
      parsedTable: "",
      checkEquipment: "",
      checkFactorIds: "",
      batchNumber: "",
      checkFactorId: "",
      flatDataList: [],
      mockData: [],
      parsedTables: [],
      reasonDialogVisible: false, // 控制弹窗显示
      resultDialogVisible: false, // 控制弹窗显示
      auditOpinion: "", // 存储审核意见
      isEditMode: false, // 编辑模式开关
      editedTables: [], // 存储编辑后的表格内容
      originalUrl: ""
    };
  },
  created() {
    this.searchForm.jobId = this.$route.query.jobId || "";
    this.handleSearch();
  },
  computed: {
    showResultColumn() {
      // 根据某种条件判断是否显示检测结果列
      // 例如：如果表格数据中有 isFactor 为 0 的数据则显示
      return this.tableData.some(row => {
        if (
          row.checkFactorInfoDetailVos &&
          Array.isArray(row.checkFactorInfoDetailVos)
        ) {
          return row.checkFactorInfoDetailVos.some(item => item.isFactor == 0);
        }
        return false;
      });
    }
  },
  methods: {
    // 获取数据
    handleSearch() {
      hisLabor.findRecordByCondition(this.searchForm).then(res => {
        console.log("query", res);
        if (res.code == 200 && res.result) {
          this.tableData = res.result.records;
          this.total = res.result.total;
        }
      });
    },

    resetForm() {
      this.searchForm.fileResourceName = "";
      this.handleSearch();
    },

    // 状态标签类型映射
    statusType(reviewType) {
      // 确保传入的值被正确处理
      const status = String(reviewType);
      switch (status) {
        case "0":
          return "info";
        case "1":
          return "success";
        case "2":
          return "danger";
        case "4":
          return "success";
        case "5":
          return "danger";
        default:
          return "";
      }
    },
    // 状态文字映射
    statusText(reviewType) {
      const status = String(reviewType);
      const map = {
        "0": "待复核",
        "1": "复核通过",
        "2": "复核驳回",
        "4": "审核通过",
        "5": "审核驳回"
      };
      const text = map[status];
      return text;
    },

    viewResult(row) {
      // 先重置数据
      this.closeResultDialog();

      // 设置当前行数据
      this.checkFactorId = row.checkFactorId || "";
      this.checkFactorIds = row.checkFactorIds || "";
      this.batchNumber = row.batchNumber || "";
      this.originalUrl = row.originalUrl || "";
      // 使用 nextTick 确保 DOM 更新后再执行异步操作
      this.$nextTick(() => {
        this.handleSearchlates();
        this.updateStyle();
        this.resultDialogVisible = true;
      });
    },
    viewAttachment(row) {
      if (!row.batchUrl || row.batchUrl === "" || row.batchUrl === null) {
        this.$message.warning("暂无附件可查看");
        return;
      }
      var url =
        this.$store.getters.sysBaseUrl +
        "/api/checkTaskGroup/downloadbatch?filenames=" +
        row.batchUrl;
      window.open(url);
    },
    viewReason(row) {
      this.auditOpinion = row.reviewExplain;
      this.reasonDialogVisible = true;
    },
    closeReasonDialog() {
      this.auditOpinion = "";
      this.reasonDialogVisible = false;
    },
    // 表单撤回方法
    withdrawForm(row) {
      this.$confirm("是否确定撤回原始记录表? ", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          hisLabor
            .revokeCheckFactor({
              checkFactorIds: row.checkFactorIds,
              batchNumber: row.batchNumber
            })
            .then(res => {
              if (res.code == 200) {
                this.$notify({
                  title: "成功",
                  message: res.message,
                  type: "success"
                });
                this.handleSearch();
                this.dialogVisible = false;
              } else {
                this.$notify({
                  title: "失败",
                  message: res.message,
                  type: "error"
                });
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消撤回");
        });
    },
    handleSearchlates() {
      const idsArray = this.checkFactorIds.split(",");

      batchesServer
        .getTemplates({
          checkFactorId: idsArray[0]
        })
        .then(res => {
          console.log("获取到的模板文件");

          // 清空之前的数据
          this.mockData = [];
          this.tableHtml = "";
          this.tableStyle = "";

          if (Array.isArray(res.result) && res.result.length > 0) {
            // 创建一个Promise数组来等待所有文件加载完成
            const promises = res.result.map(fileName => {
              return this.loadSingleFile(fileName);
            });

            // 等待所有文件加载完成
            Promise.all(promises)
              .then(results => {
                // 过滤掉null值（被略过的文件）
                const validResults = results.filter(result => result !== null);
                if (validResults.length > 0) {
                  this.combineAndRenderTables(); // 确保调用的是这个方法
                }
              })
              .catch(error => {
                console.error("加载文件过程中出错");
                this.$message.error("加载文件过程中出错");
              });
          }
        })
        .catch(error => {
          console.error("获取模板失败");
          this.$message.error("获取模板失败");
        });
    },

    loadSingleFile(fileName) {
      const fileRes = {
        pageIndex: 1,
        query: {
          checkFactorIds: this.checkFactorIds,
          batchNumber: this.batchNumber
        },
        reportName: fileName
      };

      return new Promise((resolve, reject) => {
        batchesServer
          .loadData(fileRes)
          .then(res => {
            console.log("加载文件成功:", fileName, res);

            if (
              res.result &&
              res.result.content !== undefined &&
              res.result.style !== undefined
            ) {
              const fileData = {
                fileName: fileName,
                tableHtml: res.result.content,
                tableStyle: res.result.style
              };
              this.mockData.push(fileData);
              resolve(fileData);
            } else {
              console.warn(`文件返回空数据，已略过`);
              resolve(null);
            }
          })
          .catch(error => {
            console.error("加载文件失败");
            this.$message.error(`加载文件失败`);
            reject(error);
          });
      });
    },

    combineAndRenderTables() {
      if (this.mockData.length > 0) {
        // 清空之前的数据
        this.parsedTables = [];

        // 为每个表格单独解析和渲染（按原始顺序）
        this.mockData.forEach(data => {
          this.tableHtml = data.tableHtml;
          this.tableStyle = data.tableStyle;
          const parsedTable = this.parseSingleTable();
          if (parsedTable) {
            this.parsedTables.push(parsedTable);
          }
        });
      }
    },

    parseSingleTable() {
      if (!this.tableHtml) return null;

      const parser = new DOMParser();
      const doc = parser.parseFromString(this.tableHtml, "text/html");
      const table = doc.querySelector("table");

      if (!table) return null;

      // 移除对空单元格的处理，保留所有原始内容
      // 只处理样式相关的内容

      // 应用样式
      if (this.tableStyle) {
        // 创建一个临时的样式元素来解析CSS类
        const styleElement = document.createElement("style");
        styleElement.innerHTML = this.tableStyle;
        document.head.appendChild(styleElement);

        // 遍历所有带类名的td元素，将类样式转换为内联样式
        const cells = table.querySelectorAll("td[class]");
        cells.forEach(cell => {
          const className = cell.className;
          const cssClass = this.tableStyle.match(
            new RegExp(`\\.${className}\\{([^}]+)\\}`, "i")
          );
          if (cssClass) {
            // 将CSS规则转换为内联样式
            const rules = cssClass[1].split(";");
            rules.forEach(rule => {
              if (rule.trim()) {
                const [property, value] = rule.split(":");
                if (property && value) {
                  // 处理CSS属性名，转换为camelCase
                  let propName = property
                    .trim()
                    .replace(/-([a-z])/g, g => g[1].toUpperCase());
                  cell.style[propName] = value.trim();
                }
              }
            });
          }
        });

        // 移除临时样式元素
        document.head.removeChild(styleElement);
      }

      return table.outerHTML;
    },

    parseSingleTable() {
      if (!this.tableHtml) return null;

      const parser = new DOMParser();
      const doc = parser.parseFromString(this.tableHtml, "text/html");
      const table = doc.querySelector("table");

      if (!table) return null;

      // 应用样式
      if (this.tableStyle) {
        // 创建一个临时的样式元素来解析CSS类
        const styleElement = document.createElement("style");
        styleElement.innerHTML = this.tableStyle;
        document.head.appendChild(styleElement);

        // 遍历所有带类名的td元素，将类样式转换为内联样式
        const cells = table.querySelectorAll("td[class]");
        cells.forEach(cell => {
          const className = cell.className;
          const cssClass = this.tableStyle.match(
            new RegExp(`\\.${className}\\{([^}]+)\\}`, "i")
          );
          if (cssClass) {
            // 将CSS规则转换为内联样式
            const rules = cssClass[1].split(";");
            rules.forEach(rule => {
              if (rule.trim()) {
                const [property, value] = rule.split(":");
                if (property && value) {
                  // 处理CSS属性名，转换为camelCase
                  let propName = property
                    .trim()
                    .replace(/-([a-z])/g, g => g[1].toUpperCase());
                  cell.style[propName] = value.trim();
                }
              }
            });
          }
        });

        // 移除临时样式元素
        document.head.removeChild(styleElement);
      }

      return table.outerHTML;
    },
    updateStyle() {
      if (this.batchNumber && this.batchNumber != "") {
        batchesServer
          .getCheckFactorByBatchNumberDetail({
            batchNumber: this.batchNumber,
            checkFactorIds: this.checkFactorIds
          })
          .then(res => {
            if (res.code === 200) {
              // 将 checkRes 转换为对象
              const resultData = res.result;
              this.projectName = res.result[0].projectName;
              this.inspectionName = res.result[0].inspectionName;
              if (resultData && Array.isArray(resultData)) {
                resultData.forEach(item => {
                  // 处理主因子
                  if (item.checkRes && typeof item.checkRes === "string") {
                    try {
                      item.checkRes = JSON.parse(item.checkRes);
                    } catch (e) {
                      console.warn("checkRes 解析失败:", e);
                      item.checkRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                    }
                  } else if (!item.checkRes) {
                    item.checkRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                  }

                  // 处理因子套餐中的 checkSubRes (注意：factorSubsetVos 是对象而不是数组)
                  if (item.factorSubsetVos) {
                    // 如果 factorSubsetVos 是对象
                    if (!Array.isArray(item.factorSubsetVos)) {
                      const subItem = item.factorSubsetVos;
                      if (
                        subItem.checkSubRes &&
                        typeof subItem.checkSubRes === "string"
                      ) {
                        try {
                          subItem.checkSubRes = JSON.parse(subItem.checkSubRes);
                        } catch (e) {
                          console.warn("checkSubRes 解析失败:", e);
                          subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                        }
                      } else if (!subItem.checkSubRes) {
                        subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                      }
                    }
                    // 如果 factorSubsetVos 是数组
                    else if (Array.isArray(item.factorSubsetVos)) {
                      item.factorSubsetVos.forEach(subItem => {
                        if (
                          subItem.checkSubRes &&
                          typeof subItem.checkSubRes === "string"
                        ) {
                          try {
                            subItem.checkSubRes = JSON.parse(
                              subItem.checkSubRes
                            );
                          } catch (e) {
                            console.warn("checkSubRes 解析失败:", e);
                            subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                          }
                        } else if (!subItem.checkSubRes) {
                          subItem.checkSubRes = { name: "", v1: "", v2: "" }; // 设置默认结构
                        }
                      });
                    }
                  }
                });
              }
              this.batchData = resultData;
            }
          });
      }
    },
    formatEquipmentInfo(equipmentStr) {
      console.log(equipmentStr);

      try {
        // 解析JSON字符串
        const equipment = JSON.parse(equipmentStr);

        // 按照 equipmentName - equipmentModel - equipmentNumber 格式显示
        return `${equipment.equipmentName || ""} - ${equipment.equipmentModel ||
          ""} - ${equipment.equipmentNumber || ""}`;
      } catch (e) {
        // 如果解析失败，直接返回原始字符串
        return equipmentStr;
      }
    },
    closeResultDialog() {
      try {
        // 重置所有相关数据
        this.checkEquipment = "";
        this.flatDataList = [];
        this.batchData = [];
        this.parsedTables = [];
        this.mockData = [];
        this.tableHtml = "";
        this.tableStyle = "";
        this.checkFactorIds = "";
        this.checkFactorId = "";
        this.batchNumber = "";
        this.originalUrl = "";
        // 设置弹窗关闭
        this.resultDialogVisible = false;
      } catch (error) {
        // 即使出错也强制关闭弹窗
        this.resultDialogVisible = false;
      }
    },
    beforeDestroy() {
      // 组件销毁前清理事件监听器
      if (this.isEditMode) {
        this.disableTableEditing();
      }
    },
    toggleEditMode() {
      if (
        !this.originalUrl ||
        this.originalUrl === "" ||
        this.originalUrl === null
      ) {
        this.$message.warning("暂无实验室原始记录表可查看");
        return;
      }
      var url =
        this.$store.getters.sysBaseUrl +
        "/api/checkTaskGroup/downloadbatch?filenames=" +
        this.originalUrl;
      window.open(url);
    }
  }
};
</script>

<style scoped lang="scss">
.reason-content {
  font-size: 14px;

  .checkStatus-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
  }

  .checkStatus-label {
    font-weight: bold;
  }

  .checkStatus-value {
    font-weight: bold;
  }

  .opinion-item {
    margin-top: 10px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}

.left-form {
  flex: 2;
  padding: 20px;
  overflow-y: auto; /* 添加垂直滚动条 */
  border-right: 1px solid #ddd;
  max-height: 100vh; /* 限制最大高度 */
  height: auto; /* 自动高度 */
  min-height: 500px; /* 最小高度 */
}

.right-form {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background: #dedede;
  overflow-y: scroll; /* 改为scroll确保滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}

.sample-group {
  /* 确保内容可以滚动 */
  overflow-y: auto;
  max-height: calc(100vh - 200px); /* 根据需要调整，减去其他元素的高度 */
}

.dynamic-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.dynamic-table td {
  padding: 8px;
  border: 1px solid #ccc;
  text-align: left;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: inline-block;
  width: 100px;
  font-weight: bold;
}

.form-group input[type="text"],
.form-group select,
.form-group input[type="number"] {
  padding: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.button-group {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  /* 防止按钮组被滚动影响 */
  flex-shrink: 0;
}

.button-group button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button-group button:nth-child(1) {
  background-color: #ccc;
}

.button-group button:nth-child(2) {
  background-color: #007bff;
  color: white;
}

.button-group button:nth-child(3) {
  background-color: #28a745;
  color: white;
}
.table-divider {
  margin: 20px 0;
  border-top: 1px dashed #ccc;
}

.factor-single {
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.right-form .el-form-item {
  margin-bottom: 0px !important;
}

.factor-package {
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
}

.factor-package-item {
  background-color: #ffffff;
  border: 1px solid #e0e9f0;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
  border-radius: 15px;
}

.factor-package-item:hover {
  background-color: #f5faff;
  box-shadow: 0 1px 4px rgba(64, 158, 255, 0.15);
  border-radius: 15px;
}

.factor-single:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.factor-package:hover {
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

/* 为编辑模式下的空单元格添加更好的视觉提示 */
.dynamic-table.edit-mode td:empty:before {
  content: "\00a0"; /* 使用非断行空格作为占位符 */
  visibility: hidden;
}

.dynamic-table.edit-mode td:focus:empty:before {
  content: ""; /* 聚焦时清除占位符 */
}

/* 可选：为编辑模式下的空单元格添加虚线边框提示 */
.dynamic-table.edit-mode td:empty {
  border: 1px dashed #ccc !important;
}
</style>
